<?php
class DBBase extends LightConnection
{
	/**
	 * QueryHelp
	 *
	 * @var QueryHelp
	 */
	public $tableQuery;

	
	public $fk = 'id';	
	
	public $name = '';
	
	protected $table = '';
	
	public function DBBase()
	{
		parent::__construct($context);
		
		if(!$this->name)
		{
			throw new HtmlStudioException(280, 'Model está sem tabela definida');
		}
		if(!$this->table)		
			$this->table = $this->name;
		
		$this->table = strtolower($this->table);
		$this->tableQuery = new QueryHelp($this->table);		
	}	
	
	public function Save($dados)
	{
		$dados = $this->processData($dados);
		if($dados)
		{
			if($dados[$this->fk])
			{				
				$this->processUpdate($dados);
				
			}else
			{
				$sql = $this->tableQuery->Insert($dados);
				$this->Query($sql->SQL,$sql->prepare);
				return $this->LasId();
			}
		}
	}	
	
	public function Query($sql, $prepare = null, $oneLine = false)
	{
		return parent::Query($sql, $prepare , $oneLine)->ResultArray();
	}
	
	
	public function Delete($valor)
	{	
		$filtro  = new QueryFilter();
		$filtro->addFilter($this->fk,$valor);
		$sql = $this->tableQuery->Delete($filtro);		
		return $this->Query($sql->SQL,$sql->prepare);		
	}
	
	public function Update($dados)
	{		
		$dados = $this->processData($dados);
		$this->processUpdate($dados);
	}
	
	public function findForId($id)
	{		
		$filtro  = new QueryFilter();
		$filtro->addFilter($this->fk, $id);		
		return $this->select($filtro, true);			
	}
	
	/**
	 * Todos campos
	 *
	 * @return Array
	 */
	public function all($filtro = '')
	{
		return $this->select($filtro);		
	}
	
	public function allForLanguage($lang, $field)
	{
		$filtro  = new QueryFilter();
		$filtro->addFilter($field,$lang);		
		return $this->select($filtro);	
	}
	
	/**
	 * Pega os campos com a consulta formatada
	 *
	 * @param QueryFilter $filtro
	 * @return DBIterator
	 */
	public function select($filtro = "", $onLine = false)
	{
		$arrayPrepare = array();
		
		if(!empty($filtro->field))
			$sql = "SELECT $filtro->field FROM $this->table";
		else
			$sql = "SELECT * FROM $this->table";
			
		$sql .= ' WHERE 1 = 1 ';
		
		if(count($filtro->arrayFields))
		{
			foreach ($filtro->arrayFields as $fieldName => $fields) 
			{
				$sql .= $fields[0] . ' ' . $fieldName . ' ' . $fields[1] . ' ? ';	
				$arrayPrepare[] = $fields[2];		
			}
		}
		
		if($filtro->command)
		{
			$sql .= " " . $filtro->command;
		}
		//DebugUtil::PrintValue($arrayPrepare);
		//echo $sql;exit;
		return $this->Query($sql,$arrayPrepare, $onLine);
	}	
	
	private function processData($data)
	{
		if(!empty($data[$this->name]))
			return $data[$this->name];
		return false;
	}
	
	private function processUpdate($dados)
	{
		if($dados)
		{
			$filtro  = new QueryFilter();
			$filtro->addFilter($this->fk, $dados[$this->fk]);
			unset($dados[$this->fk]);
			$sql  = $this->tableQuery->Update($dados,$filtro);
			$this->Query($sql->SQL,$sql->prepare); 
		}
	}
	
	public function pagination($display = array())
	{
		if(!empty($display['filter']))
		{
			$filtro = $display['filter'];
			$filtroTotal = $display['filter'];
		}
		else
		{
			$filtro = new QueryFilter();
			$filtroTotal = new QueryFilter();
		}
		
		$prepare = !empty($display['prepare'])?$display['prepare']:array();
		if(!empty($display['sql']))
		{				
			$toFrom = strstr(strtolower($display['sql']), 'from');		
			$total = $this->Query('Select count(*) as total ' . $toFrom, $prepare,true);			
		}
		else
		{		
			$filtro->field =  ' count(*) as total';
			$total = $this->select($filtroTotal,true);			
		}
		
		$total = $total['total'];			
	

		if(!empty($display['limit']))
			$limit = $display['limit'];	
		else
			$limit = 50;	
						
		$parametre  = !empty($display['parameterPage'])?$display['parameterPage']:'pg';
		$paging = $this->resultPaging($parametre,$total,$limit);
		
		$sqlLimit = " limit $paging->start, $limit";		
		
		if(!empty($display['sql']))
		{	
			$all = $this->Query($display['sql'] . $sqlLimit ,$prepare);
		}
		else
		{
			$filtro->field = '';
			$filtro->command .= $sqlLimit;
			$all = $this->select($filtro);
		}
			
		$url = $this->_context->webroot();		
		$url = $url . $this->_context->getModule() . '/' . $this->_context->getAction();
			
		$pagination = new Pagination($url, $paging->limit);
		$pagination->setParametrePage($parametre);
		
		$post = !empty($display['post'])?$display['post']:false;
		$pagination->setPost($post);
		$pagination->setPage($paging->page,$paging->total);
		$pagination->setParametre($display['parametres']);
		$pagination->setId(rand(100,10000));
		
		$display = !empty($display['pagination'])? $display['pagination']: array();
		$pagination->setDisplay($display);	
	
		
//
		
		//DebugUtil::PrintValue($filtroTotal,'Line:'.__LINE__ . ' Class:'.__CLASS__);
		
		//DebugUtil::PrintValue($filtro,'Line:'.__LINE__ . ' Class:'.__CLASS__);
		
	//	DebugUtil::PrintValue($all,'Line:'.__LINE__ . ' Class:'.__CLASS__);	
		//exit;
		//
		//DebugUtil::PrintValue($total,'Line:'.__LINE__ . ' Class:'.__CLASS__);		
	
		
		//$controller = $this->_context->getController();
		
		//$action = $this->_context->getAction();
	
		
		
		
		$html = 
		
		$dados = array();
		$dados['total']= $total;
		$dados['result'] = $all;
		$dados['pagination'] = $pagination->mount();
		
		return $dados;
		//$this->paginacao->setId($idTable . "_form");
		//$grid["PAGINATION"] = $this->paginacao->mount();
		
		//DebugUtil::PrintValue($html,'Line:'.__LINE__ . ' Class:'.__CLASS__);
		
		exit;
	}
	
	protected function resultPaging($parametre,$total, $limit)
	{
		$pg = $this->_context->ContextValue($parametre);
		if(empty($pg))
		{
			$pg = 1;
		}		
		return  new Paging($total, $limit, $pg);		
	}	
}
class Paging
{	
	var $page;
	var $limit;
	var $total;
	var $start;
	var $end;
	var $pages;
	
	function Paging($total, $limit, $page)
	{
		$this->page = $page;
		$this->limit = $limit;
		$this->total = $total;

		$this->pages = ceil($this->total/$this->limit);
		if ($this->page > $this->pages)
		{
			$this->page = $this->pages;
		}
		$this->start = abs(($this->page * $this->limit) - $this->limit);		
		$this->end = $this->page * $this->limit;		
	}
}
?>